package app.yj.channel.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.gyf.barlibrary.ImmersionBar;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;
import com.vise.xsnow.event.BusManager;
import com.vise.xsnow.event.IEvent;
import com.vise.xsnow.event.Subscribe;

import app.yj.channel.ChannelCache;
import app.yj.channel.R;
import app.yj.channel.event.FinishBrowerEvent;
import app.yj.channel.event.FinishSplashEvent;
import app.yj.channel.event.UpdateBrowerUrlEvent;
import tech.com.commoncore.base.BaseActivity;
import tech.com.commoncore.utils.DataUtils;
import tech.com.commoncore.utils.ToastUtil;
import tech.com.commoncore.utils.brower.SonicJavaScriptInterface;
import tech.com.commoncore.utils.brower.SonicRuntimeImpl;
import tech.com.commoncore.utils.brower.SonicSessionClientImpl;

/**
 * Author:ChenPengBo
 * Date:2019/6/30
 * Desc:WebView专用Brower
 * Version:1.0
 */
public class WebViewActivity extends BaseActivity {
    public static final String URL = "url";
    public static final String BLACKORWHITE = "blackOrWhite";
    public static final String VERSIONCOL = "versionCol";

    WebView webView;
    ProgressBar progressWeb;
    private String url;
    private int blackOrWhite;
    private String versionCol;

    private SonicSession sonicSession;

    private ImmersionBar mImmersionBar;

    @Override
    public int getContentLayout() {
        return R.layout.channel_activity_brower;
    }

    @Override
    public void beforeSetContentView() {
        super.beforeSetContentView();
        url = getIntent().getStringExtra(URL);
        blackOrWhite = getIntent().getIntExtra(BLACKORWHITE, 0);
        versionCol = getIntent().getStringExtra(VERSIONCOL);
        if (DataUtils.isEmpty(versionCol)) {
            //如果传的颜色为空,则采取默认方案
            versionCol = "#000000";
            blackOrWhite = 1;
        }
    }

    long curTime = 0;
    @Override
    public void onBackPressed() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();
        } else{
            if(System.currentTimeMillis() - curTime <1000){
                super.onBackPressed();
            }else{
                curTime = System.currentTimeMillis();
                ToastUtil.show("再次点击退出");
            }
        }
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        webView = findViewById(R.id.webview);
        progressWeb = findViewById(R.id.progress_web);

        if (ChannelCache.isIsFinishBrowerAndGoApp()) {
            finish();
            return;
        }

        if (!TextUtils.isEmpty(ChannelCache.getWebUrl())) {
            url = ChannelCache.getWebUrl();
        }
        // init sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        SonicSessionClientImpl sonicSessionClient = null;

        // if it's sonic mode , startup sonic session at first time
        // sonic mode
        SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
        sessionConfigBuilder.setSupportLocalServer(true);

        // if it's offline pkg mode, we need to intercept the session connection


        // create sonic session and run sonic flow
        sonicSession = SonicEngine.getInstance().createSession(url, sessionConfigBuilder.build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
            // throw new UnknownError("create session fail!");
            //            Toast.makeText(this, "create sonic session fail!", Toast.LENGTH_LONG).show();
        }
        Intent intent = getIntent();
        // add java script interface
        // note:if api level lower than 17(android 4.2), addJavascriptInterface has security
        // issue, please use x5 or see https://developer.android.com/reference/android/webkit/
        // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)
        webView.getSettings().setJavaScriptEnabled(true);
        webView.removeJavascriptInterface("searchBoxJavaBridge_");
        intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis());
        webView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "sonic");

        initWebView();  //初始化webview设置
        // webview is ready now, just tell session client to bind
        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(webView);
            sonicSessionClient.clientReady();
        } else { // default mode
            webView.loadUrl(url);
        }
    }

    private void initWebView(){

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                String s =url;
//                Log.e("url = ----",s);
                if (!TextUtils.isEmpty(url) && url.endsWith(".apk")) {
                    downloadByBrowser(url);
                    return true;
                }

                if(!url.startsWith("http")){
                    try {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(s));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
//                        ToastUtil.show("应用未安装");
                    }
                    return true;
                }
                return super.shouldOverrideUrlLoading(view,url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
            }
            //            @Override
//            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//                //用javascript隐藏系统定义的404页面信息
////                Log.e("url fail",failingUrl);
//                //用javascript隐藏系统定义的404页面信息
////                String data = "Page NO FOUND！";
////                view.loadUrl("javascript:document.body.innerHTML=\"" + data + "\"");
//            }

        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress >= 100) {
                    progressWeb.setVisibility(View.GONE); // 加载完毕进度条消失
                } else {
                    progressWeb.setProgress(newProgress); // 更新进度
                }
                super.onProgressChanged(view, newProgress);
            }
        });

        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setDefaultFixedFontSize(14);
        webView.getSettings().setDisplayZoomControls(false);
        webView.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webView.requestFocus();

        //解决图片不显示
        webView.getSettings().setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    }


    private void downloadByBrowser(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    @Override
    public void loadData() {
        super.loadData();
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.statusBarView(R.id.top_view)
                .fullScreen(false);
        if (versionCol != null && versionCol.toLowerCase().contains("0x")) {  // 如果INT类型,16进制
            try {
                String lowCase = versionCol.toLowerCase();
                String colorValue = lowCase.substring(2, versionCol.length());
                mImmersionBar.statusBarColor("#" + colorValue);
                if (blackOrWhite == 0) {
                    mImmersionBar.statusBarDarkFont(true);
                } else {
                    mImmersionBar.statusBarDarkFont(false);
                }
                //                if (colorValue.startsWith("f")) {
                //                    mImmersionBar.statusBarDarkFont(true);
                //                } else {
                //                    mImmersionBar.statusBarDarkFont(false);
                //                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (versionCol != null && versionCol.toLowerCase().contains("#")) {  //如果 # 16进制
            try {
                mImmersionBar.statusBarColor(versionCol);

                String lowCase = versionCol.toLowerCase();
                String colorValue = lowCase.substring(1, versionCol.length());
                //                if (colorValue.startsWith("f")) {
                //                    mImmersionBar.statusBarDarkFont(true);
                //                } else {
                //                    mImmersionBar.statusBarDarkFont(false);
                //                }
                if (blackOrWhite == 0) {
                    mImmersionBar.statusBarDarkFont(true);
                } else {
                    mImmersionBar.statusBarDarkFont(false);
                }
                //
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //不做处理,默认值.
        }

        mImmersionBar.init();
    }


    public static Intent actionToActivity(Context context, String url, int blackOrWhite, String versionCol) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(URL, url);
        intent.putExtra(BLACKORWHITE, blackOrWhite);
        intent.putExtra(VERSIONCOL, versionCol);
        return intent;
    }

    @Override
    protected void onDestroy() {
        BusManager.getBus().post(new FinishSplashEvent());
        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
        if (mImmersionBar != null) {
            mImmersionBar.destroy();
        }
        if(webView!=null){
            ViewParent parent =  webView.getParent();
            if(parent!=null){
                ((ViewGroup)parent).removeView(webView);
            }
            webView.stopLoading();
            webView.getSettings().setJavaScriptEnabled(false);
            webView.clearHistory();
            webView.removeAllViews();
            try {
                webView.destroy();
                webView= null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }


    @Override
    public boolean isRegisterEvent() {
        return super.isRegisterEvent();
    }

    @Subscribe
    public void onEvent(IEvent event) {
        if (event instanceof UpdateBrowerUrlEvent) {
            startActivity(actionToActivity(mContext, ((UpdateBrowerUrlEvent) event).newUrl, blackOrWhite, versionCol));
            finish();
        } else if (event instanceof FinishBrowerEvent) {
            //进入主页
            finish();
        }
    }

}
